const config = require('./config.js');
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

const ajax = (url, data, succ) => {
  data = data || {};
  url = config.baseUrl + url;
  data.token = wx.getStorageSync('token');
  wx.showLoading({
    title: '努力加载中...',
    mask: true,
  })
  wx.request({
    url,
    method:'post',
    data,
    success: function(res) {
      let data = res.data;
      if (data.code === 0) {
        succ(data);
      } else {
        wx.showToast({
          title: data.msg
        })
      }
    },
    fail: function() {
      wx.showToast({
        title: '网络异常'
      })
    },
    complete: function() {
      wx.hideLoading();
    }
  })
}

module.exports = {
  ajax,
  formatTime: formatTime
}